package org.example.aaaatest.a3;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;
import java.util.Collections;
import java.util.UUID;

public class DistributedLock {
    private Jedis jedis;          // Redis 客户端
    private String lockKey;       // 锁的键
    private String lockValue;     // 锁的值（唯一标识）
    private int expireTime;       // 锁的过期时间（毫秒）

    public DistributedLock(Jedis jedis, String lockKey, int expireTime) {
        this.jedis = jedis;
        this.lockKey = lockKey;
        this.expireTime = expireTime;
        this.lockValue = UUID.randomUUID().toString(); // 生成唯一标识
    }

    // 尝试获取锁
    public boolean tryLock() {
        // 使用 SET NX PX 命令原子性加锁
        SetParams params = SetParams.setParams().nx().px(expireTime);
        String result = jedis.set(lockKey, lockValue, params);
        return "OK".equals(result); // 返回是否成功
    }

    // 释放锁（Lua 脚本保证原子性）
    public void unlock() {
        String script = 
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "    return redis.call('del', KEYS[1]) " +
            "else " +
            "    return 0 " +
            "end";
        jedis.eval(script, Collections.singletonList(lockKey), 
                   Collections.singletonList(lockValue));
    }
}

